package logic

import (
	"context"
	"encoding/base64"

	"greet/internal/svc"
	"greet/internal/types"
	"greet/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type CodeEncryptLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCodeEncryptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CodeEncryptLogic {
	return &CodeEncryptLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CodeEncryptLogic) CodeEncrypt(req *types.CodeEncryptRequest) (resp *types.CodeEncryptResponse, err error) {
	if req.Type == "SM4" {
		key, _ := base64.StdEncoding.DecodeString(req.Data["key"])
		iv, _ := base64.StdEncoding.DecodeString(req.Data["iv"])
		cipherText, err := utils.Encrypt([]byte(req.Data["plainText"]), key, iv)
		if err != nil {
			return &types.CodeEncryptResponse{
				Code:    "error",
				Message: err.Error(),
			}, nil
		}
		return &types.CodeEncryptResponse{
			Code: "success",
			Data: map[string]string{
				"cipherText": base64.StdEncoding.EncodeToString(cipherText),
			},
		}, nil
	}

	return
}
